<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MlsShareForm
 *
 * @author Poh Nean
 */
class MlsShareForm extends CFormModel
{

	public $share_with_agency;
	public $share_with_contacts;
	public $share_with_emails;
	public $contacts;
	public $emails;

	public function rules()
	{
		return array(
			array('share_with_agency, share_with_contacts, share_with_emails', 'validateMethods'),
			array('share_with, contacts, email', 'safe'),
			array('emails', 'validateEmails')
		);
	}
	
	public function validateMethods() {
		if ($this->share_with_agency == null && $this->share_with_contacts == null && $this->share_with_emails == null) {
			$this->addError('share_with_agency', 'You must choose at least one sharing method');
		}
	}

	public function validateEmails()
	{
		if (!empty($this->emails)) {
			$emails = explode(',', $this->emails);

			if (!empty($emails)) {
				$validator = new CEmailValidator;

				foreach ($emails as $email) {
					$email = trim($email);
					if (!$validator->validateValue($email)) {
						$this->addError('emails', 'An invalid email address is given.');
					}
				}
			}
		}
	}

	public function getSelectedContactsListData() {
		if (empty($this->contacts)) {
			return array();
		}
		
		$criteria = new CDbCriteria();
		$criteria->addInCondition('id', $this->contacts);
		$criteria->compare('t.user_id', Yii::app()->user->id);
		$criteria->compare('t.deleted', 0);
		
		$selectedContacts = Contact::model()->findAll($criteria);
		
		$listData = array();
		if (!empty($selectedContacts)) {
			foreach ($selectedContacts as $selectedContact) {
				$listData[$selectedContact->id] = $selectedContact->name . ' <' . $selectedContact->email . '>';
			}
		}
		
		return $listData;
	}
}

?>
